package com.winhxd.b2c.customer.service.impl;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.AppConstant;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.constant.CustomerConstant;
import com.winhxd.b2c.common.context.CustomerUser;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.model.CustomerDistributorLevel;
import com.winhxd.b2c.common.domain.customer.model.CustomerInvitationRecord;
import com.winhxd.b2c.common.domain.customer.model.CustomerUserInfo;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorTypeAndChannelVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerUserInfoSimpleVO;
import com.winhxd.b2c.common.domain.system.login.condition.CustomerUserInfoCondition;
import com.winhxd.b2c.common.domain.system.user.condition.CheckUserCondition;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.mq.MQDestination;
import com.winhxd.b2c.common.mq.StringMessageSender;
import com.winhxd.b2c.common.util.GeneratePwd;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.dao.CustomerUserInfoMapper;
import com.winhxd.b2c.customer.service.CustomerLoginService;
import com.winhxd.b2c.customer.service.DistributorChannelService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author wufuyun
 * @date 2018年8月3日 上午10:03:32
 * @Description 微信登录业务实现
 * @version
 */
@Service
public class CustomerLoginServiceImpl implements CustomerLoginService {
	private static final Logger logger = LoggerFactory.getLogger(CustomerLoginServiceImpl.class);
	@Autowired
	private CustomerUserInfoMapper customerUserInfoMapper;
	@Autowired
	DistributorChannelService channelService;
	@Autowired
	private Cache cache;
	@Autowired
	StringMessageSender stringMessageSender;
	@Autowired
	private UserServiceClient userServiceClient;

	@Override
	public int saveLoginInfo(CustomerUserInfo customerUserInfo) {
		customerUserInfo.setCreated(new Date());
		int cont = customerUserInfoMapper.insertSelective(customerUserInfo);
		return cont;
	}

	@Override
	public int updateCustomerInfo(CustomerUserInfo customerUserInfo) {
		customerUserInfo.setUpdated(new Date());
		int cont = customerUserInfoMapper.updateByPrimaryKeySelective(customerUserInfo);
		return cont;
	}

	@Override
	public int removeCustomerInfo(Long customerId) {
		return customerUserInfoMapper.deleteByPrimaryKey(customerId);
	}

	@Override
	public CustomerUserInfo getCustomerUserInfoByCondition(CustomerUserInfoCondition condition) {
		return customerUserInfoMapper.selectCustomerUserInfoByCondition(condition);
	}

	@Override
	public CustomerUserInfo getCustomerUserInfoById(Long customerId) {
		return customerUserInfoMapper.selectByPrimaryKey(customerId);
	}

	@Override
	public CustomerUserInfo findCustomerUserByLevel() {
		CustomerUserInfoCondition condition = new CustomerUserInfoCondition();
		condition.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_3.getCode());
		return customerUserInfoMapper.selectCustomerUserInfoByCondition(condition);
	}

	@Override
	public CustomerUserInfoSimpleVO getCustomerUserInfoSimpleVO(CustomerUserInfo customer) {
		CustomerUserInfoSimpleVO vo= new CustomerUserInfoSimpleVO();
		if(StringUtils.isEmpty(customer.getToken())){
			CustomerUserInfo token = new CustomerUserInfo();
			token.setId(customer.getId());
			token.setToken(GeneratePwd.getRandomUUID());
			token.setUpdatedBy(customer.getId());
			token.setUpdated(new Date());
			token.setUpdatedByName(customer.getWechatName());
			customerUserInfoMapper.updateByPrimaryKeySelective(token);
			vo.setToken(token.getToken());
		}else{
			vo.setToken(customer.getToken());
		}
		vo.setCustomerMobile(customer.getCustomerMobile()==null?"":customer.getCustomerMobile());
		vo.setWechatName(customer.getWechatName());
		vo.setWechatImg(customer.getHeadImg());
		vo.setUserLevel(customer.getLevel());
		vo.setCustomerId(customer.getId());
		vo.setBindStatus(customer.getBindStatus()==null? CustomerConstant.BIND_STATUS:customer.getBindStatus().intValue());
		CustomerUserInfo userParent = findCustomerUserByLevel();
		if(userParent.getId().equals(customer.getParentId()) && CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode().intValue()==customer.getLevel().intValue()){
			vo.setMemberStatus(1);
		}else{
			vo.setMemberStatus(0);
		}
		CustomerDistributorTypeAndChannelVO channelVO = channelService.getDistributerChannelLevelById(customer.getChannelId());
		if(channelVO!=null){
			List<CustomerDistributorLevel> levelList = channelVO.getDistributorLevelList();
			CustomerUserInfo finalCustomerUserInfo = customer;
			levelList.forEach(l -> {
				if(finalCustomerUserInfo.getLevel().intValue()==l.getLevel()){
					vo.setLevelNickName(l.getLevelName());
				}
			});
		}
		CustomerUser user = new CustomerUser();
		user.setCustomerId(customer.getId());
		user.setLevel(customer.getLevel());
		user.setOpenid(customer.getOpenid());
		//设置缓存
		cache.set(CacheName.CUSTOMER_USER_INFO_TOKEN + customer.getToken(), JsonUtil.toJSONString(user));
		cache.expire(CacheName.CUSTOMER_USER_INFO_TOKEN + customer.getToken(),
				AppConstant.LOGIN_APP_TOKEN_EXPIRE_SECOND);
		logger.info("CustomerUserInfoSimpleVO:{}",JsonUtil.toJSONString(vo));
		return vo;
	}

	@Override
	public void bindOriginalRelation(Long masterId, String masterOpenId, CustomerUserInfo userSlave) {
		//保存会员原始关系
		CustomerInvitationRecord record = new CustomerInvitationRecord();
		//保存原始关系 保存的是分享过来的iD
		record.setMasterId(masterId);
		record.setMasterWechatId(masterOpenId);
		record.setSlaveId(userSlave.getId());
		record.setSlaveWechatId(userSlave.getOpenid());
		String recordString = JsonUtil.toJSONString(record);
		stringMessageSender.send(MQDestination.INVITATION_RECORD_MESSAGE, recordString);
	}

	@Override
	public void checkMobileAndAccount(Long id, String mobile) {
		if(customerUserInfoMapper.countCheckMobileNumber( id,mobile)>0){
			throw new BusinessException(BusinessCode.CODE_1027);
		}
		CheckUserCondition userCondition = new CheckUserCondition();
		userCondition.setAccount(mobile);
		ResponseResult<SysUser> result = userServiceClient.getSysUserByCondition(userCondition);
		if(result.getCode()!=0){
			throw new BusinessException(BusinessCode.CODE_1001);
		}else{
			SysUser sysUser = result.getData();
			if(sysUser!=null && !sysUser.getCustomerId().equals(id)){
				throw new BusinessException(BusinessCode.CODE_1027);
			}
		}
	}

}
